<?php

namespace app\http\controller\admin\general;

use app\model\AssetsModel;
use app\http\controller\admin\Controller;

/**
 * 资源控制器
 */
class AssetsController extends Controller
{
    /**
     * 资源管理
     *
     * @return string
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $option = $this->request->get();
            $result = AssetsModel::instance()->queryList($option);
            return $this->success('ok', $result['list'], ['count' => $result['total']]);
        }

        return $this->fetch('general/assets/index', [
            'storage' => AssetsModel::instance()->storageTxt,
            'status'  => AssetsModel::instance()->statusTxt,
        ]);
    }

    /**
     * 新增资源
     *
     * @return string
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $option = $this->request->post();
            $add = AssetsModel::instance()->add($option, $this->userInfo['id']);
            if (!$add) {
                return $this->error(AssetsModel::instance()->getError());
            }

            return $this->success('ok');
        }
        return $this->fetch('general/assets/add');
    }

    /**
     * 编辑资源
     *
     * @return string
     */
    public function edit()
    {
        $idx = $this->request->get('idx', 0);
        $data = AssetsModel::instance()->getInfo(['id' => $idx]);
        if (!$data) {
            return $this->error(AssetsModel::instance()->getError());
        }

        if ($this->request->isAjax() && $this->request->isPost()) {
            $option = $this->request->post();
            $option['idx'] = $idx;
            $edit = AssetsModel::instance()->edit($option, $idx);
            if (!$edit) {
                return $this->error(AssetsModel::instance()->getError());
            }

            return $this->success('ok');
        }


        return $this->fetch('general/assets/edit', ['data' => $data]);
    }

    /**
     * 获取开放的资源
     *
     * @return string
     */
    public function select()
    {
        $option = $this->request->get();
        $option['status'] = 1;
        $result = AssetsModel::instance()->queryList($option);
        return $this->success('ok', $result['list'], ['count' => $result['total']]);
    }
}
